import { processColor } from 'react-native'
import update from 'immutability-helper'
import {ListView} from 'react-native'
import { Toast } from 'antd-mobile'
import {RefreshState} from '../widgets'
import { createAction, NavigationActions } from '../utils/index'
import * as newsService from '../services/newsService'

const initState = {
  innerData:[],
  currentPage: 0,
  dataSource: new ListView.DataSource({ rowHasChanged: (r1, r2) => r1 !== r2 }).cloneWithRows([]),
  twoInnerData: [],
  twoCurrentPage: 0,
  twoDataSource: new ListView.DataSource({ rowHasChanged: (r1, r2) => r1 !== r2 }).cloneWithRows([]),
}

export default {
  namespace: 'news',
  state: initState,
  reducers: {
    modifyState(state, { payload }) {
      return { ...state, ...payload }
    },
    initState(state, { payload }) {
      return {...initState}
    }
  },
  effects: {
    *init({payload}, {put, call, select}) {
      const callback = payload.callback
      yield put(createAction("initState")())
      callback()
    },
    *fetchNewsList({payload}, { put , call, select}) {
      const newsState = yield select(state => state.news)
      const resp = yield call(newsService.getNewsList, {
        currentPage: newsState.currentPage,
        clzz: 0
      })
      if (resp.resultCode !== 200) {
        Toast.info(resp.msg, 1)
        return false
      }
      const rData = resp.data || {}
      const respData = rData['data'] || []
      if(respData.length === 0) {
        payload.listView.endRefreshing(RefreshState.NoMoreData)
      } else {
        const newD = newsState.innerData.concat(respData)
        yield put(createAction("modifyState")({
          innerData: newD,
          dataSource: newsState.dataSource.cloneWithRows(newD),
          currentPage: newsState.currentPage + 1
        }))
        payload.listView.endRefreshing(RefreshState.Idle)
      }
    },
    *fetchTwoNewsList({payload}, { put, call, select}) {
      console.log('fetch two news list')
      const newsState = yield select(state => state.news)
      const resp = yield call(newsService.getNewsList, {
        currentPage: newsState.twoCurrentPage,
        clzz: 1
      })
      if (resp.resultCode !== 200) {
        Toast.info(resp.msg, 1)
        return false
      }
      const rData = resp.data || {}
      const respData = rData['data'] || []
      if(respData.length === 0) {
        payload.listView.endRefreshing(RefreshState.NoMoreData)
      } else {
        const newD = newsState.twoInnerData.concat(respData)
        yield put(createAction("modifyState")({
          twoInnerData: newD,
          twoDataSource: newsState.twoDataSource.cloneWithRows(newD),
          twoCurrentPage: newsState.twoCurrentPage + 1
        }))
        payload.listView.endRefreshing(RefreshState.Idle)
      }
    }
  },
  subscriptions: {
  },
}
